package cn.agiledata.bank.linkbank.impl.validate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.agiledata.bank.linkbank.exception.LinkBankException;

/**
 * 时间格式校验器
 * 
 * @author maxianbo
 * 
 */
public final class TimeFormatValidator extends AbstractFieldValidator {
    private String format;

    public void setFormat(String format) {
        this.format = format;
    }

    public void validate(String value) throws LinkBankException {
        if (value == null) {
            validateNullable(value);
        } else if ("".equals(value)) {
            validateEmptiable(value);
        } else {
            SimpleDateFormat formator = new SimpleDateFormat(this.format);
            try {
                if (value.length() != this.format.length()) {
                    throw new ParseException("The length is unmatched",
                            this.format.length());
                }
                formator.parse(value);
            } catch (ParseException e) {
                String example = formator.format(new Date());
                throw LinkBankException.getFormatUnmatchException(getTarget(),
                        value, this.format, example, getErrorCode());
            }
        }
    }

}
